package com.fjec.activity.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.activity.entity.BizUserGiftChangeRecord;
import com.fjec.activity.feign.MarketClient;
import com.fjec.activity.mapper.BizUserGiftChangeRecordMapper;
import com.fjec.activity.service.IBizUserGiftChangeRecordService;
import com.google.common.base.Strings;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 008.用户礼物变化记录表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-18
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class BizUserGiftChangeRecordServiceImpl extends ServiceImpl<BizUserGiftChangeRecordMapper, BizUserGiftChangeRecord> implements IBizUserGiftChangeRecordService {

    @Resource
    private BizUserGiftChangeRecordMapper mapper;

    @Autowired
    private MarketClient marketClient;

    @Override
    public Map<String, Object> changeRecords(Integer searchBy, String title, Integer busiType, Integer opeType, String startTime, String endTime, Page page) {
        List<Map<String, Object>> data;
        Map<String, Object> result = new HashMap<>();
        if (!Strings.isNullOrEmpty(title) && searchBy == 1) {
            List<Long> userIds = marketClient.getUserIdByBusiNameES(title);
            if (userIds.size() == 0) {
                result.put("data", new ArrayList<>());
                result.put("total", 0);
                return result;
            }
            data = mapper.changeRecords(userIds, null, busiType, opeType, startTime, endTime, page);
        } else if (!Strings.isNullOrEmpty(title) && searchBy == 2) {
            data = mapper.changeRecords(null, Long.valueOf(title), busiType, opeType, startTime, endTime, page);
        } else {
            data = mapper.changeRecords(null, null, busiType, opeType, startTime, endTime, page);
        }

        // 获取busiName
        List<Long> busiIdOrUserIds = data.stream()
                                            .map(d -> MapUtils.getLong(d, "busiIdOrUserId"))
                                            .collect(Collectors.toList());
        List<Map<String, Object>> busiNames = marketClient.getBusiNamesByBusiIdOrUserIds(busiIdOrUserIds);
        List<Map<String, Object>> giftInfos = marketClient.getGiftInfo(3);
        data.forEach(d -> {
            // 店铺或公司名称
            Long id = MapUtils.getLong(d, "busiIdOrUserId");
            Optional<Map<String, Object>> opt = busiNames.stream()
                    .filter(bn -> (MapUtils.getLong(bn, "busiId").equals(id) || (MapUtils.getLong(bn, "userId").equals(id)))).findFirst();
            opt.ifPresent(map -> d.put("busiName", MapUtils.getString(map, "busiName")));

            // 礼物信息
            StringBuilder giftAndNums = new StringBuilder();
            String giftIdStr = MapUtils.getString(d, "giftId");
            List<String> giftIds = Arrays.asList(giftIdStr.split(","));
            String giftNumStr = MapUtils.getString(d, "changeNum");
            List<String> giftNums = Arrays.asList(giftNumStr.split(","));
            for (int i = 0; i < giftIds.size(); i++) {
                Long giftId = Long.valueOf(giftIds.get(i));
                Integer changeNum = Integer.valueOf(giftNums.get(i));
                // 礼物名称
                Optional<Map<String, Object>> gInfo = giftInfos.stream().filter(g -> MapUtils.getLong(g,"Id").equals(giftId)).findFirst();
                if (gInfo.isPresent()) {
                    Map<String, Object> gi = gInfo.get();
                    String giftName = MapUtils.getString(gi, "ServName");
                    giftAndNums.append(giftName).append("x").append(Math.abs(changeNum)).append(",");
                }
            }

            d.put("gifts", giftAndNums.deleteCharAt(giftAndNums.length() - 1).toString());

        });

        // todo: 礼物购买和礼物兑换 相关信息

        result.put("data", data);
        result.put("total", page.getTotal());
        return result;
    }
}
